﻿using Rainbow_Game_Fans.Common;
using Rainbow_Game_Fans.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using UmengSocialSDK;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

//“中心应用程序”模板在 http://go.microsoft.com/fwlink/?LinkID=391641 上有介绍

namespace Rainbow_Game_Fans
{
    /// <summary>
    /// 显示组内某一项的详细信息的页面。
    /// </summary>
    public sealed partial  class ItemPage : Page
    {
        private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();

        ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

        public ItemPage()
        {
            this.InitializeComponent();
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
            this.navigationHelper.GoBackCommand = new RelayCommand(() =>
            {
                if (WebView_Item.CanGoBack)
                {
                    WebView_Item.GoBack();
                }
                else
                {
                    //转到退出游戏确认
                    ShowDialog_Exit();
                    //this.navigationHelper.GoBack();
                }

            }, this.navigationHelper.CanGoBack);

        }

        /// <summary>
        /// 获取与此 <see cref="Page"/> 关联的 <see cref="NavigationHelper"/>。
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// 获取此 <see cref="Page"/> 的视图模型。
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源；通常为 <see cref="NavigationHelper"/>。
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 字典。首次访问页面时，该状态将为 null。</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: 创建适用于问题域的合适数据模型以替换示例数据
            var item = await SampleDataSource.GetItemAsync((string)e.NavigationParameter);
            this.DefaultViewModel["Item"] = item;


        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="sender">事件的来源；通常为 <see cref="NavigationHelper"/>。</param>
        ///<param name="e">提供要使用可序列化状态填充的空字典
        ///的事件数据。</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: 在此处保存页面的唯一状态。
        }

        #region NavigationHelper 注册

        /// <summary>
        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// <para>
        /// 应将页面特有的逻辑放入
        /// <see cref="NavigationHelper.LoadState"/>
        /// 和 <see cref="NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在早期会话期间保留的页面状态之外，
        /// LoadState 方法中还提供导航参数。
        /// </para>
        /// </summary>
        /// <param name="e">提供导航方法数据和
        /// 无法取消导航请求的事件处理程序。</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
            if (localSettings.Values["slider_brightness_Value"] != null)
            {
                WebView_Item.Opacity = (double)localSettings.Values["slider_brightness_Value"];
            }
            
        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
            WebView_Item.Navigate(new Uri("ms-appx-web:///HTML5/BlankPage.html"));
        }



        #endregion

        private void WebView_Item_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            ProgressBar_Item.Visibility = Windows.UI.Xaml.Visibility.Visible;
            loading.Visibility = Windows.UI.Xaml.Visibility.Visible;
            Storyboard_loading.Begin();
        }

        private void WebView_Item_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            if (args.IsSuccess == true)
            {
                ProgressBar_Item.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                loading.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                Storyboard_loading.Stop();

            }
        }

        #region  退出游戏是弹出确认
        async void ShowDialog_Exit()
        {
            ContentDialog dialog = new ContentDialog()
            {
                Title = "退出当前游戏？", //标题
                Content = "",//内容
                FullSizeDesired = false,  //是否全屏展示
                PrimaryButtonText = "确定",//第一个按钮内容
                SecondaryButtonText = "取消"
            };
            dialog.Background = new SolidColorBrush(Colors.Red);
            if (localSettings.Values["slider_brightness_Value"] != null)
            {
                dialog.Opacity = (double)localSettings.Values["slider_brightness_Value"];
            }
            dialog.SecondaryButtonClick += dialog_SecondaryButtonClick;//第二个按钮单击事件
            dialog.PrimaryButtonClick += dialog_PrimaryButtonClick;

            ContentDialogResult result = await dialog.ShowAsync();
            if (result == ContentDialogResult.Primary) { } //处理第一个按钮的返回
            else if (result == ContentDialogResult.Secondary) { }//处理第二个按钮的返回

        }
        void dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            //await new MessageDialog("您选择了第一个按钮").ShowAsync();
            this.navigationHelper.GoBack();
        }
        void dialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            //await new MessageDialog("您选择了第二个按钮").ShowAsync();
        }
        #endregion


        //UmengText text = new UmengText("Good Job!") { Title = "Music" };
        //private async void flscr_share_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        //{
        //    //对 WebView 中的内容截图，并将原始图像数据放入内存流
        //    InMemoryRandomAccessStream share_img = new InMemoryRandomAccessStream();
        //    await WebView_Item.CapturePreviewToStreamAsync(share_img);

        //    // 显示原始截图
        //    //BitmapImage bitmapImage = new BitmapImage();
        //    //bitmapImage.SetSource(share_img);
        //    //imageOriginal.Source = bitmapImage;

        //    //转换为数据流发送
        //    var reader = new DataReader(share_img.GetInputStreamAt(0));
        //    var bytes_imageData = new byte[share_img.Size];
        //    await reader.LoadAsync((uint)share_img.Size);
        //    reader.ReadBytes(bytes_imageData);
        //    //byte[] imageData = new byte[imageStream.Length];
        //    //byte[] imageData = ConvertToBytes(bitmapImage);
        //    //imageStream.Read(imageData, 0, imageData.Length);
        //    UmengPicture picture = new UmengPicture(bytes_imageData, "I like it!") { Title = "彩虹游戏迷" };
        //    //UmengClient umengClient = new RenrenClient(Config.UmengAppKey);
        //    List<UmengClient> clients = new List<UmengClient>()
        //    {
        //        new SinaWeiboClient(Config.UmengAppKey),
        //        new RenrenClient(Config.UmengAppKey),
        //        new QzoneClient(Config.UmengAppKey),
        //        new TencentWeiboClient(Config.UmengAppKey),
        //        new DoubanClient(Config.UmengAppKey),
        //        //new WeixinClient(Config.UmengAppKey, Your_WeiXin_AppId),                
        //        //new FaceBookClient(Config.UmengAppKey, Your_Facebook_AppId),
        //        //new TwitterClient(Config.UmengAppKey, Your_Twitter_ApiKey, Your_Twitter_ApiSecret)            
        //    };

        //    UmengClient umengClient = new MultiClient(clients);
            
        //    var res = await umengClient.SharePictureAsync(picture);
        //    //await umengClient.ShareTextAsync(text);
        //}

    }
    
}
      
